package dice_machine

import (
	"errors"
	"gorm.io/gorm"
	global2 "longmen/server/config/global"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/timehelper"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/mysql/models/models_report"
	"longmen/server/pkg/db/redis/cache"
	"time"
)

type DiceUser struct {
	UserId int
}

func NewDiceUser(userId int) (d *DiceUser) {
	return &DiceUser{UserId: userId}
}

func (d *DiceUser) Check(i *input) error {
	if i.betNum <= 0 {
		return errors.New(global2.Lang.T("insufficient_balance_or_invalid_amount"))
	}
	userInfo, _ := cache.GetUserFullInfo(d.UserId)
	if userInfo.Gold < i.betNum {
		return errors.New(global2.Lang.T("insufficient_balance"))
	}
	return nil
}

func (d *DiceUser) ChangeBalance(i *input, r *result) error {
	err := global2.GetX().Transaction(func(tx *gorm.DB) error {
		chBalance := r.RewardNum - i.betNum //变动金额
		profitLog := d.genProfit(d.UserId, chBalance)
		beforeAmount, afterAmount, err := db_main.UpdateAmountByTx(d.UserId, chBalance, _const.CoinGold, tx, _const.WALLET_BALANCE_SHOW, profitLog)
		if err != nil {
			return err
		}
		flow := &models_report.GameDiceFlow{
			Uid:           int64(d.UserId),
			Ctime:         time.Now().Unix(),
			AwardAmount:   chBalance,
			BeforeBalance: beforeAmount,
			AfterBalance:  afterAmount,
			Choices:       i.choices,
			BetNum:        i.betNum,
			IsRollDown:    i.isRollDown,
			RollNum:       r.RollNum,
			Odds:          r.Odds,
			IsReward:      r.IsReward,
			RewardNum:     r.RewardNum,
			Tag:           i.tag,
		}
		cache.UpdateUserGoldCache(d.UserId, int64(afterAmount))
		return tx.Create(&flow).Error
	})
	return err
}

// 生成用户消费流水
func (d *DiceUser) genProfit(userId int, coinCount int) []*models_main.UserProfit {
	userProfit := &models_main.UserProfit{
		Uid:         userId,
		CoinCount:   coinCount,
		Content:     util.GetConsumeName(25),
		Type:        _const.FINANCE_DEBIT,
		ConsumeType: _const.GAME_FRUIT_BET,
		Resid:       0,
		Count:       1, //数量为1
		CreateTime:  time.Now(),
		CoinType:    _const.FEE_TYPE_GOLD,
		FUid:        0, //没有收款人，所以前台不显示收款人是谁
		OrderNo:     util.GenOrderId("DICE", 1),
		Liveid:      0,
	}
	var profitLog []*models_main.UserProfit
	profitLog = append(profitLog, userProfit)
	return profitLog
}

func (d *DiceUser) GetDiceFlow(page, size int, dateSt, dateEd string) (int64, int, int, []models_report.GameDiceFlow, error) {
	var res []models_report.GameDiceFlow
	var total int64
	betRewardTotal := struct {
		BetNumTotal    int `json:"bet_num_total"`
		RewardNumTotal int `json:"reward_num_total"`
	}{}
	if page <= 0 {
		page = 1
	}
	if size <= 0 {
		size = 10
	}
	dateStStamp, _ := timehelper.INaDay2Unix(dateSt)
	_, dateEdStamp := timehelper.INaDay2Unix(dateEd)
	if (dateEdStamp-dateStStamp)/(60*60*24) > 31 {
		return 0, 0, 0, nil, errors.New("时间范围过大")
	}
	err := global2.GetR().Model(models_report.GameDiceFlow{}).Where("user_id = ? and ctime between ? and ? ", d.UserId, dateStStamp, dateEdStamp).Count(&total).Offset((page - 1) * size).Limit(size).Order("id desc").Find(&res).Error
	if err != nil {
		global2.Log.Errorf("GetDiceFlow err:%v", err)
	}
	err = global2.GetR().Model(models_report.GameDiceFlow{}).Where("user_id = ? and ctime between ? and ? ", d.UserId, dateStStamp, dateEdStamp).
		Select("sum(bet_num) as bet_num_total, sum(reward_num-bet_num) as reward_num_total").Order("id desc").Find(&betRewardTotal).Error
	if err != nil {
		global2.Log.Errorf("GetDiceFlow err:%v", err)
	}
	return total, betRewardTotal.BetNumTotal, betRewardTotal.RewardNumTotal, res, nil
}

func (d *DiceUser) GetDiceBatchReward(tag string) *batchResp {
	resp := batchResp{}
	if len(tag) <= 0 {
		return &resp
	}
	err := global2.GetR().Model(models_report.GameDiceFlow{}).Where("user_id = ? and tag = ? ", d.UserId, tag).Select("sum(award_amount) as batch_award_num, count(id) as batch_times").Find(&resp).Error
	if err != nil {
		global2.Log.Errorf("GetDiceBatchReward err:%v", err)
	}
	return &resp
}
